package com.zzz.dynamicds.service.impl;

import com.alibaba.fastjson.JSON;
import com.zzz.dynamicds.annotation.Master;
import com.zzz.dynamicds.annotation.Slave;
import com.zzz.dynamicds.dao.CommonDao;
import com.zzz.dynamicds.entity.CompareResult;
import com.zzz.dynamicds.service.CommonService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.zzz.dynamicds.utils.CommonUtils.getAllTableName;
import static com.zzz.dynamicds.utils.CommonUtils.getTableDiffs;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2019/7/1 0001
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private CommonDao commonDao;


    @Override
    @Master
    public Set<String> getAllField1(String tableName, String schemaName) {
        return commonDao.getAllFields(tableName, schemaName);
    }

    @Override
    @Slave
    public Set<String> getAllField2(String tableName, String schemaName) {
        return commonDao.getAllFields(tableName, schemaName);
    }

    @Override
    public String getTableDiff() {
        String[] allTableName = getAllTableName();
        List<CompareResult> compareResultList = new ArrayList<>();
        for (int i = 0; i < allTableName.length; i++) {
            CommonService currentProxy = (CommonService) AopContext.currentProxy();
            Set<String> oldTable = currentProxy.getAllField1(allTableName[i], "6.27_test");
            Set<String> newTable = currentProxy.getAllField2(allTableName[i], "bj_zh_6.27");
            CompareResult compareResult = getTableDiffs(allTableName[i], oldTable, newTable);
            if (compareResult.getDiffs().size() > 0) {
                compareResultList.add(compareResult);
            }
        }
        return JSON.toJSONString(compareResultList);
    }

}
